package com.ruoyi.common.utils;

import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * @author cyh
 * @date 2022/5/23 4:43 下午
 */
@Slf4j
public class MyBeanUtil {

    /**
     * copy 源对象 值为null的字段
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target) {
        //获取源对象的所有字段
        Field[] sourceFields = source.getClass().getDeclaredFields();
        try {
            //遍历
            for (int i = 0; i < sourceFields.length; i++) {
                sourceFields[i].setAccessible(true);
                String name = sourceFields[i].getName();
                if (Func.isEmpty(sourceFields[i].get(source))) {
                    try {
                        Field declaredField = target.getClass().getDeclaredField(name);
                        declaredField.setAccessible(true);
                        Object tValue = declaredField.get(target);
                        if (Func.isNotEmpty(tValue)) {
                            tValue.getClass().getTypeName();
                            sourceFields[i].set(source, tValue);
                            log.info("Set:", tValue);
                        }
                        declaredField.setAccessible(false);
                    } catch (NoSuchFieldException e) {
                        log.warn(target.getClass().getName() + "不存在字段：" + name);
                    }
                }
                sourceFields[i].setAccessible(false);
            }
        } catch (IllegalAccessException e) {
            log.error("copyPropertiesErr", e);
        }
    }
}
